<template>
    <div class="page-header">
        <span class="page-title" style="display: flex;align-items: center;gap: 16px;">
            用能户管理
            <el-input v-model="searchTerm" clearable placeholder="搜索用能户..." class="search-input"
                @input="handleSearch" />
        </span>
        <el-button type="primary" @click="showAddDialog">
            添加用能户
        </el-button>
    </div>
    <div class="energy-users-container">
        <el-row :gutter="16" v-loading="loading">
            <template v-if="filteredEnergyUsers.length > 0">
                <el-col :xs="24" :sm="24" :xl="12" v-for="user in filteredEnergyUsers" :key="user.id">
                    <area-card :name="user.name" :water-meters="getMetersByType(user.id, 1)"
                        :electric-meters="getMetersByType(user.id, 2)" :gas-meters="getMetersByType(user.id, 3)">
                        <!-- 左侧信息区域 -->
                        <template #info>
                            <div class="user-info">
                                <div class="ratio-info">
                                    <span class="label">不明水分摊比例:</span>
                                    <span class="value">{{ user.unknown_ratio }}%</span>
                                </div>
                                <el-tag :type="Number(user.unknown_ratio) > 0 ? 'success' : 'info'" class="tag-margin">
                                    {{ Number(user.unknown_ratio) > 0 ? '参与分摊' : '不参与分摊' }}
                                </el-tag>
                            </div>
                        </template>
                        <!-- 定制标题栏操作按钮 -->
                        <template #actions>
                            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(user)">编辑</el-button>
                            <el-button type="danger" size="small" :icon="Delete"
                                @click="handleDelete(user)">删除</el-button>
                        </template>
                    </area-card>
                </el-col>
            </template>
            <template v-else>
                <el-col :span="24">
                    <el-empty description="暂无用能户数据" :image-size="200">
                        <template #description>
                            <p>暂无用能户数据，请点击"添加用能户"创建</p>
                        </template>
                        <el-button type="primary" @click="showAddDialog">添加用能户</el-button>
                    </el-empty>
                </el-col>
            </template>
        </el-row>

        <!-- 编辑/添加用能户对话框 -->
        <el-dialog draggable v-model="showDialog" :title="isNewRow ? '添加用能户' : '编辑用能户'" width="30%"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form>
                <el-form-item label="用能户名称">
                    <el-input v-model="editingName" ref="editInput" @keyup.enter="handleSave" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelEdit">取消</el-button>
                    <el-button type="primary" @click="handleSave">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, nextTick, watch, } from 'vue'
import { useCompanyStore } from '@/stores/company'
import { createEnergyUsersApi, deleteEnergyUsersApi, updateEnergyUsersApi } from '@/api/energy_users'
import { getMeterInfoApi } from '@/api/meter'
import { handleError } from '@/utils/handleError'
import { debounce } from '@/utils/DebounceAndThrottle'
import { useEnergyUsersStore } from '@/stores/energyUser'
import AreaCard from '@/components/card/BlockCard.vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// store
const energyUsersStore = useEnergyUsersStore()
const companyStore = useCompanyStore()

// 直接在组件中管理状态，避免递归更新问题
const loading = ref(false)
const searchTerm = ref('')
const energyUserList = ref([])
const filteredEnergyUsers = ref([])

// 编辑状态管理
const editingId = ref(null)
const editingName = ref('')
const editingRatio = ref(0)
const isNewRow = ref(false)
const showDialog = ref(false)
const editInput = ref(null)

// 表计数据
const metersData = ref([])

// 加载用能户数据
const loadEnergyUsers = async () => {
    loading.value = true
    try {
        await energyUsersStore.fetchEnergyUsers()
        energyUserList.value = [...energyUsersStore.energyUserList]
        updateFilteredUsers()
    } catch (error) {
        handleError(error, '加载用能户数据失败')
    } finally {
        loading.value = false
    }
}

// 更新筛选后的用户列表
const updateFilteredUsers = () => {
    if (!searchTerm.value) {
        filteredEnergyUsers.value = [...energyUserList.value]
    } else {
        filteredEnergyUsers.value = energyUserList.value.filter(user =>
            user.name.toLowerCase().includes(searchTerm.value.toLowerCase())
        )
    }
}

// 获取表计数据
const fetchMetersData = async () => {
    try {
        const res = await getMeterInfoApi({
            company_id: companyStore.currentCompany.id
        })
        metersData.value = res.data
    } catch (error) {
        handleError(error, '获取表计数据失败')
    }
}

// 按类型获取用能户的表计
const getMetersByType = (energyUserId, type) => {
    if (!metersData.value || !energyUserId) return []
    return metersData.value.filter(meter => meter.energy_user_id === energyUserId && meter.type === type)
}

// 处理搜索
const handleSearch = debounce(() => {
    updateFilteredUsers()
}, 300)

// 检查名称是否重复
const checkNameDuplicate = (name, currentId) => {
    return energyUserList.value.some(user =>
        user.name === name && user.id !== currentId
    )
}

// 显示添加对话框
const showAddDialog = () => {
    editingId.value = null
    editingName.value = ''
    editingRatio.value = 0
    isNewRow.value = true
    showDialog.value = true

    nextTick(() => {
        if (editInput.value) {
            editInput.value.focus()
        }
    })
}

// 处理编辑
const handleEdit = (row) => {
    editingId.value = row.id
    editingName.value = row.name
    isNewRow.value = false
    showDialog.value = true

    nextTick(() => {
        if (editInput.value) {
            editInput.value.focus()
        }
    })
}

// 取消编辑
const cancelEdit = () => {
    editingId.value = null
    editingName.value = ''
    editingRatio.value = 0
    isNewRow.value = false
    showDialog.value = false
}

// 处理保存
const handleSave = async () => {
    const trimmedName = editingName.value.trim()

    // 如果是空值
    if (!trimmedName) {
        ElMessage.warning('用能户名称不能为空')
        return
    }

    // 检查重复
    if (checkNameDuplicate(trimmedName, editingId.value)) {
        ElMessage.error('用能户名称不能重复')
        return
    }

    // 检查编辑前后值是否相同
    if (!isNewRow.value) {
        const currentUser = energyUserList.value.find(user => user.id === editingId.value)
        if (currentUser && trimmedName === currentUser.name) {
            cancelEdit()
            return
        }
    }

    loading.value = true
    try {
        if (isNewRow.value) {
            await createEnergyUsersApi({
                company_id: companyStore.currentCompany.id,
                name: trimmedName,
            })
            ElMessage.success('添加成功')
        } else {
            await updateEnergyUsersApi({
                id: editingId.value,
                name: trimmedName,
            })
            ElMessage.success('保存成功')
        }
        // 重新加载数据
        await loadEnergyUsers()
        await fetchMetersData()

        cancelEdit()
    } catch (error) {
        handleError(error, isNewRow.value ? '添加用能户失败' : '保存用能户失败')
    } finally {
        loading.value = false
    }
}

// 处理删除
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm('确认删除该用能户吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        })

        loading.value = true
        try {
            await deleteEnergyUsersApi({
                id: '' + row.id
            })
            await loadEnergyUsers()
            await fetchMetersData()
            ElMessage.success('删除成功')
        } catch (error) {
            handleError(error, '删除用能户失败')
        } finally {
            loading.value = false
        }
    } catch {
        // 用户取消操作
    }
}

// 监听搜索词变化
watch(searchTerm, () => {
    updateFilteredUsers()
})

// 监听公司变化
watch(() => companyStore.currentCompany?.id, async (newVal) => {
    if (newVal) {
        await fetchMetersData()
        await loadEnergyUsers()
    }
}, { immediate: true })

</script>

<style scoped>
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.title {
    font-size: 18px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 16px;
}

.energy-users-container {
    position: relative;
}

.header-operations {
    display: flex;
    gap: 16px;
    align-items: center;
    margin-bottom: 16px;
}

.search-input {
    width: 200px;
}

.user-info {
    display: flex;
    flex-direction: column;
    gap: 12px;
    padding: 8px 0;
    height: 100%;
}

.tag-margin {
    width: fit-content;
    margin-top: 8px;
}

.ratio-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.label {
    font-size: 14px;
    color: #606266;
}

.value {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
}
</style>